package com.umpay.sp.saas.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.umpay.sp.web.util.PropertyUtil;

public class DubboInvokerUtil
{
	private static Logger logger = LoggerFactory.getLogger(DubboInvokerUtil.class);
	
	//Application
	private static ApplicationConfig application = null;
	//regitryConfig default protocol zookeeper
	private static RegistryConfig registry = null;
	
	private static String applicationName = null;
	private static String registryProtocol = null;
	private static String registryAddress = null;
	private static String serviceGroup = null;

	static
	{
		logger.info("初始化Dubbo参数！");
		
		serviceGroup = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties", "dubbo.consumer.group","saas");
//		System.out.println(serviceGroup);
		application = new ApplicationConfig();
		applicationName = "OperationPlatService-Provider";//PropertyUtil.getStrValue("spEnterpriseWeb_config.properties", "dubbo.application.name");		//调用的resin or 项目中配置分离？
		System.out.println(applicationName);
		application.setName(DubboInvokerUtil.isEmpty(applicationName) ? "OperationPlatWeb-Consumer" :  applicationName);
		// registry config
		registry = new RegistryConfig();
		registryProtocol = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties", "dubbo.registry.protocol", "zookeeper");
		System.out.println(registryProtocol);
		registryAddress = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties", "zookeeper.address");
		System.out.println(registryAddress);
		if(!registryAddress.contains("zookeeper"))
		{
			registry.setProtocol(registryProtocol);
		}
		registry.setAddress(registryAddress);
	}

	public static <T> T getInvoker(Class<T> clazz)
	{
		// invoke remote service
		ReferenceConfig<T> reference = new ReferenceConfig<T>();
		reference.setRegistry(registry);
		reference.setApplication(application);
		reference.setInterface(clazz);
		if(!isEmpty(serviceGroup))
			reference.setGroup(serviceGroup);
		reference.setRetries(0);
		return reference.get(); 
	}
	
	public static boolean isEmpty(String string)
	{
		return string == null || string.trim().length() == 0;
	}

}
